package com.atguigu.crowd.util;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CrowdUtil {
    /**
     * 判断Http请求是否是ajax请求
     *
     * @param request HttpServletRequest
     * @return boolean
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String contentType = request.getHeader("Content-Type");
        String xRequestWith = request.getHeader("X-Requested-With");

        return (contentType != null && contentType.contains("application/json"))
                || ("XMLHttpRequest".equals(xRequestWith));
    }

    /**
     * md5加密
     *
     * @param source 明文
     * @return  加密结果
     */
    public static String md5(String source) {
        if (source == null || source.length() == 0) {
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        final String algorithm = "md5";
        final int signNum = 1;
        final int radix = 16;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte[] input = source.getBytes(StandardCharsets.UTF_8);
            byte[] output = messageDigest.digest(input);
            BigInteger bigInteger = new BigInteger(signNum, output);

            return bigInteger.toString(radix).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }
}
